package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"strconv"
	"strings"
	"test/models"
	"time"
)

type ShopController struct {
	beego.Controller
}

func (c *ShopController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 10)
	key := "shop-" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()
	pageData := make(map[string]interface{})
	if err != nil {
		var count int64
		query := models.DB.Model(&models.Shop{}).Count(&count)
		var shop []models.Shop
		offset := (page - 1) * size
		err = query.Offset(offset).Limit(size).Find(&shop).Error
		pageData["count"] = count
		pageData["shop"] = shop
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "数据查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			marshal, _ := json.Marshal(&pageData)
			value := string(marshal)
			models.Rdb.Set(key, value, time.Second*10)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功",
				Data: pageData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功redis",
			Data: pageData,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	img := c.GetString("img")
	price, _ := c.GetFloat("price")
	zt := c.GetString("zt")
	if name == "" || img == "" || price == 0 || zt == "" {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "数据不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	shop := models.Shop{
		Name:  name,
		Img:   img,
		Price: price,
		Zt:    zt,
	}
	/*	models.DB.Begin()*/
	err := models.DB.Create(&shop).Error
	if err != nil {
		/*	models.DB.Rollback()*/
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "数据添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		/*models.DB.Commit()*/
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "数据添加成功",
			Data: shop,
		}
		c.ServeJSON()

	}
}

func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Where("ID = ?", id).Delete(&models.Shop{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}

}

func (c *ShopController) Put() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	img := c.GetString("img")
	price, _ := c.GetFloat("price")
	zt := c.GetString("zt")
	shop := models.Shop{
		Name:  name,
		Img:   img,
		Price: price,
		Zt:    zt,
	}
	err := models.DB.Where("ID = ?", id).Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "数据修改成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "数据修改成功",
			Data: shop,
		}
		c.ServeJSON()

	}
}

func (c *ShopController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "请上传文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	ext := strings.ToLower(filepath.Ext(header.Filename)) //截取文件后缀 tolower变小写
	allowExt := map[string]bool{
		".png":  true,
		".jpeg": true,
	}
	if !allowExt[ext] {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "文件格式错误，必须是png,jpg,jepg格式",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if header.Size > 5*1024*1024 {
		c.Data["jaon"] = JsonR{
			Code: 500,
			Msg:  "文件超过5M请从新上传",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["jaon"] = JsonR{
			Code: 500,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		img := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "文件上传成功",
			Data: img,
		}
		c.ServeJSON()
	}

}

func (c *ShopController) Info() {
	id, _ := c.GetInt("id")
	Rankkey := "Rank"
	models.Rdb.ZIncrBy(Rankkey, 1, strconv.Itoa(id))
	key := "shop-" + strconv.Itoa(id)
	val, err := models.Rdb.Get(key).Result()
	var shop models.Shop
	if err != nil {
		err = models.DB.Model(&models.Shop{}).Where("ID = ?", id).First(&shop).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "详情展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			marshal, _ := json.Marshal(shop)
			value := string(marshal)
			models.Rdb.Set(key, value, 0)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "详情展示成功-mysql",
				Data: shop,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &shop)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "详情展示成功-redis",
			Data: shop,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) Rank() {
	key := "Rank"
	rank, err := models.Rdb.ZRevRange(key, 0, 10-1).Result()
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "排行榜获取失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	var shop []models.Shop
	for _, i := range rank {
		var shops models.Shop
		err = models.DB.Model(models.Shop{}).Where("ID=?", i).First(&shops).Error
		if err != nil {
			break
		}
		shop = append(shop, shops)
	}
	c.Data["json"] = JsonR{
		Code: 200,
		Msg:  "展示成功",
		Data: shop,
	}
	c.ServeJSON()
}
